using System;
using System.Configuration;
using log4net;
using Spring.Context;
using Spring.Context.Support;

namespace Sedna.Core.Controller
{

	public class SpringContextFactory
	{
		private ILog log = LogManager.GetLogger(typeof(SpringContextFactory));
		private IApplicationContext ctx;

		private SpringContextFactory()
		{
			try
			{
				log.Debug("SpringContextFactory enter");
			    //ctx = new XmlApplicationContext(ConfigurationSettings.AppSettings["spring.context.url"]);
				string contextUrl = ConfigurationManager.AppSettings["spring.context.url"];
				if(contextUrl != null && string.Empty != contextUrl)
				{
					//ctx = new WebApplicationContext(contextUrl);
					ctx = new XmlApplicationContext(contextUrl);
                    log.Debug("SpringContextFactory: XmlApplicationContext");
                }
				else
				{
                    log.Debug("SpringContextFactory: WebApplicationContext");
                    ctx = WebApplicationContext.Current;
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine("Exception :" + ex.StackTrace);
				log.Error("Spring Config Error", ex);
				throw;
			}
            log.Debug("SpringContextFactory finish");
        }

		private static SpringContextFactory instance;

		public static IApplicationContext GetContext()
		{
		    if (instance==null)
		    {
                instance = new SpringContextFactory();
		    }
			return instance.ctx;
		}

	}
}
